<template>
    <div style="height: 100%; overflow: hidden">
      <!-- 标题 -->
       <header class="py-4 flex items-center">
          <div class="w-1/3 flex items-center">
            <n-button strong secondary>文章标题</n-button>
            <n-input placeholder="输入文章标题" show-count clearable maxlength="100" v-model:value="title"/>
          </div>
          <div class="flex items-center ml-4">
            <n-button strong secondary>新闻日期</n-button>
            <n-date-picker v-model:value="news_date" type="date" />
          </div>
          <div class="ml-4 flex">
            <n-button strong secondary>新闻标签</n-button>
            <n-select class="w-[13rem]" v-model:value="publish_tag" :options="tagList" />
          </div>
       </header>
       <section class="pb-4 flex">
        <div class="flex w-24 text-base justify-center items-center">
          <n-button strong secondary @click="uploadCover">
            封面上传
          </n-button>
        </div>
        <n-select
              class="w-1/3"
              size="medium"
              placeholder="请选择一种上传方式"
              v-model:value="switchUpload"
              :options="options"
          >
          </n-select>
        <!-- 封面上传 -->
        <n-modal
          v-model:show="showModal"
          class="custom-card"
          preset="card"
          title="上传封面"
          size="huge"
          style="width: 30%;"
          :bordered="false"
        >
        <!-- 从新闻中获取图片 -->
         <main v-if="switchUpload == 1">
              <div class="grid grid-cols-3 grid--rows-3 h-24 w-full">
                <n-image
                  :key="index"
                  v-for="(item, index) in localImg"
                  width="100"
                  :src="item"
                />
              </div>
              <p class="pt-5 flex items-center">
                <n-text class="mr-3">选择那张图片作为封面</n-text>
                <n-input-number
                  v-model:value="imgId"
                  :min="1"
                  :max="localImg.length"
                />
              </p>
              <footer class="py-3 flex justify-end px-2">
                <n-button class="mr-2" @click="cancelUploadLink">取消</n-button>
                <n-button type="primary" @click="uploadLocalImg">确定</n-button>
              </footer>
         </main>
        <!-- 上传本地图片 -->
        <main class="flex justify-center items-center h-full" v-if="switchUpload == 2">
          <input 
              type="file" 
              accept="image/*" 
              ref="uploadFile"
              hidden
              @change="uploadLocalImageFinsh"
            />
          <n-card class="w-1/2" @click.stop="uploadFile.click()">
            <!-- 上传图片 -->
             <template v-if="!uploadType">
                <n-icon size="40">
                  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512"><path fill="none" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round" stroke-width="32" d="M256 112v288"></path><path fill="none" stroke="currentColor" stroke-linecap="square" stroke-linejoin="round" stroke-width="32" d="M400 256H112"></path></svg>
                </n-icon>
                <n-text>点击上传</n-text>
             </template>
             <!-- 上传成功 -->
            <template v-else>
              <n-image-group show-toolbar-tooltip>
                <n-image :src="uploadImgSrc" width="300" height="100"></n-image>
              </n-image-group>
              <n-button tertiary circle type="success" @click.stop="uploadFile.click()">
                <template #icon>
                  <n-icon><PencilSharp /></n-icon>
                </template>
              </n-button>
            </template>

          </n-card>
        </main>
        <!-- 上传图片链接 -->
         <main v-if="switchUpload === 3">
            <n-input v-model:value="uploadImgSrc" type="text" placeholder="输入图片链接" />
            <footer class="py-3 flex justify-end px-2">
              <n-button class="mr-3" @click="cancelUploadLink">取消</n-button>
              <n-button type="primary" @click="confirmUploadLink">确定</n-button>
            </footer>
         </main>
        </n-modal>
        <!-- 文章描述 -->
        <n-input-group class="ml-2">
            <n-input-group-label>文章描述</n-input-group-label>
            <n-input placeholder="输入文章描述" :style="{ width: '35%' }" show-count clearable maxlength="100" v-model:value="desc"/>
          </n-input-group>
      </section>
      <editor
          v-model="myValue"
          :init="init"
          api-key="w90em5a27zluxcvfiubyjvhpx8qqphbclxupve7rpi2dn66s"
      ></editor>
      <!-- 底部 -->
      <footer class="text-right py-4">
          <n-button class="mr-2" strong type="error" @click="clearContent">清空</n-button>
          <n-button strong type="primary" @click="publish">发布</n-button>
      </footer>
    </div>
  </template>
   
  <script setup lang="ts">
  import {reactive, ref, onMounted} from "vue"; //全屏
  import { getCurrentInstance } from "vue";
   let {proxy} = getCurrentInstance();
  import tinymce from "tinymce/tinymce";
  import Editor from "@tinymce/tinymce-vue";
  import "tinymce/icons/default/icons";
  import "tinymce/models/dom"; // 一定要引入
  import "tinymce/themes/silver"; // 界面UI主题
  import "tinymce/plugins/image";
  import "tinymce/plugins/table";
  import "tinymce/plugins/lists"; // 列表插件
  import "tinymce/plugins/wordcount"; // 文字计数
  import "tinymce/plugins/preview"; // 预览
  import "tinymce/plugins/emoticons"; // emoji表情
  import "tinymce/plugins/emoticons/js/emojis.js"; //必须引入这个文件才有表情图库
  import "tinymce/plugins/code"; // 编辑源码
  import "tinymce/plugins/link"; // 链接插件
  import "tinymce/plugins/advlist"; //高级列表
  import "tinymce/plugins/codesample"; //代码示例
  import "tinymce/plugins/autoresize"; // 自动调整编辑器大小
  import "tinymce/plugins/quickbars"; // 光标处快捷提示
  import "tinymce/plugins/nonbreaking"; //插入不间断空格
  import "tinymce/plugins/searchreplace"; //查找替换
  import "tinymce/plugins/autolink"; //自动链接
  import "tinymce/plugins/directionality"; //文字方向
  import "tinymce/plugins/visualblocks"; //显示元素范围
  import "tinymce/plugins/visualchars"; //显示不可见字符
  import "tinymce/plugins/charmap"; // 特殊符号
  import "tinymce/plugins/nonbreaking"; //插入不间断空格
  import "tinymce/plugins/insertdatetime"; //插入日期时间
  import "tinymce/plugins/importcss"; //引入自定义样式的css文件
  import "tinymce/plugins/accordion"; // 可折叠数据手风琴模式
  import "tinymce/plugins/anchor"; //锚点
  import "tinymce/plugins/fullscreen";
  import "tinymce/plugins/media"
  onMounted(() => {
    tinymce.init({});
  })
  //定义一个对象 init初始化
  const init = reactive({
    language_url: "/tinymce/langs/zh_CN.js", // 语言包的路径，具体路径看自己的项目
    language: "zh_CN",
    skin_url: "/tinymce/skins/ui/oxide", // skin路径，具体路径看自己的项目
    height: 600,
    branding: false, // 是否禁用“Powered by TinyMCE”
    promotion: false, //去掉 upgrade
    // toolbar_sticky: true,
    // toolbar_sticky_offset: 100,
    menubar: "file edit view insert format tools table",  
    paste_data_images: true, //允许粘贴图像
    image_dimensions: false, //去除宽高属性
    plugins: "preview code nonbreaking importcss autoresize searchreplace autolink directionality code visualblocks visualchars fullscreen image media link codesample table charmap nonbreaking anchor insertdatetime advlist lists wordcount charmap quickbars emoticons accordion" , //这里的数据是在props里面就定义好了的
    toolbar: "preview | code | nonbreaking | undo redo | accordion accordionremove | blocks fontfamily fontsize| bold italic underline strikethrough ltr rtl  | align numlist bullist | link image media | table | lineheight outdent indent| forecolor backcolor removeformat | charmap emoticons | anchor codesample", //这里的数据是在props里面就定义好了的
    // 取消图片资源路径转换
    convert_urls: false,
    // table边框位0是否展示网格线
    // visual: false,
    // 超链接默认打开方式
    link_default_target: "_blank",
    link_context_toolbar: true,
    // 默认快捷菜单
    quickbars_insert_toolbar: "image codesample table code pagebreak",
    // 选中图片的快捷提示
    quickbars_image_toolbar: "alignleft aligncenter alignright | rotateleft rotateright | imageoptions",
    editimage_toolbar: "rotateleft rotateright | flipv fliph | editimage imageoptions",
    // 文字样式
    font_family_formats:
        "Arial=arial,helvetica,sans-serif; 宋体=SimSun; 微软雅黑=Microsoft Yahei; Impact=impact,chicago;", //字体
    font_size_formats: "11px 12px 14px 16px 18px 24px 36px 48px 64px 72px", //文字大小
    image_caption: true,
    editimage_cors_hosts: ["picsum.photos"],
    noneditable_class: "mceNonEditable",
    toolbar_mode: "wrap", // 工具栏模式 floating / sliding / scrolling / wrap
    // 默认样式
    content_style:
        "body { font-family:Helvetica,Arial,sans-serif; font-size:16px }p {margin:3px; line-height:24px;}",
    image_advtab: true,
    importcss_append: true,
    paste_webkit_styles: "all",
    paste_merge_formats: true,
    nonbreaking_force_tab: false,
    paste_auto_cleanup_on_paste: false,
    file_picker_types: "media",
    media_live_embeds: true,
    images_reuse_filename: true,
    // 选中文字的快捷提示
    quickbars_selection_toolbar:
        "bold italic | quicklink h2 h3 blockquote quickimage quicktable",
    // 编辑器高度自适应
    autoresize_bottom_margin: 20,
    // autoresize_overflow_padding: 16,
    min_height: 600,
    content_css: "/tinymce/skins/content/default/content.css", //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
    images_upload_handler: async function(blobInfo, progress) {
      let file = blobInfo.blob();
      if (file.size / 1024 / 1024 > 4) {
        reject({
          message: "上传失败，图片大小请控制在 4M 以内",
          remove: true,
        });
      }
    let {data} = await proxy.$http.post("/list/uploadImage",{
        file
      },{
        headers: {
          "Content-Type": "multipart/form-data",
        }
      })
      if (data.code !== 200) return proxy.$message.error("图片上传失败")
      proxy.$message.success("图片上传服务器成功")
      return data.data.url
    },
    // 上传视频
    file_picker_callback:  (cb, value, meta) => {
      if (meta.filetype === "media") {
          let input = document.createElement("input")
          input.setAttribute("type", "file")
          input.setAttribute("accept", "video/*");
          input.onchange = async function() {
            let file = this.files[0];//只选取第一个文件。如果要选取全部，后面注意做修改
            let {data: res} = await proxy.$http.post("/list/uploadVideo",{
              file
            },{
              headers: {
                "Content-Type": "multipart/form-data",
              }
            })
            if (res.code !== 200) return proxy.$message.error("视频上传失败")
            proxy.$message.success("视频上传服务器成功")
              cb(res.data.url, { text: file.name });
          }
          input.click();
          
      } else {
        proxy.$message.warning("请选择视频文件")
      }
    },
});
   
  // 外部传递进来的数据变化
  const myValue = ref("")
  const title = ref("")
  const desc = ref("")
    // 新闻时间
  let news_date = ref()
  import dayjs from 'dayjs'
   const publish = async () => {
      // 判断新闻标题有没有
      if (!news_date.value) return proxy.$message.warning("请选择新闻日期")
      if (!title.value) return proxy.$message.warning("请输入新闻标题")
      if (!desc.value) return proxy.$message.warning("请输入新闻描述")
      // 进行新闻发送
      let {data:res} = await proxy.$http.post("/list/addNews",{
        title: title.value,
        content: myValue.value,
        desc: desc.value,
        cover: uploadImgSrc.value,
        news_date: dayjs(news_date.value).format("YYYY-MM-DD"),
        tag: publish_tag.value
      })
      if (res.code !== 200) return proxy.$message.error("发布新闻失败")
      proxy.$message.success("发布新闻成功")
      // 重置新闻内容
      title.value = ''
      myValue.value = ''
      desc.value = ''
      switchUpload.value = ''
      news_date.value = null
      uploadImgSrc.value = ''
      uploadType.value = false
      publish_tag.value = '产品'
   }

  // 清空新闻编辑
  const clearContent = () => {
    myValue.value = ""
    title.value = ""
    desc.value = ""
    news_date.value = null
    uploadImgSrc.value = ''
    uploadType.value = false
    switchUpload.value = ''
  }

  // 选择封面上传
  const switchUpload = ref<string|number>()
  const options = [
    {
      label: "从新闻内容中选择图片",
      value: 1
    },
    {
      label: "上传本地图片",
      value: 2
    },
    {
      label: "上传图片链接",
      value: 3
    }
  ]
  // 上传图片封面
  const localImg = ref([])
  const uploadCover = () => {
    if (!switchUpload.value) return proxy.$message.warning("请选择上传方式")
    if (switchUpload.value === 1) {
      let pathList = myValue.value.match(/<img.*?src="(.*?)"/g) as any
      if (!pathList) return proxy.$message.warning("新闻内容中没有图片")
      localImg.value = pathList.map(item => item.match(/src="(.*?)"/)[1])
    }
    showModal.value = true
  }
  // 从本地上传图片
  import {PencilSharp} from '@vicons/ionicons5'
  let uploadFile = ref()
  const uploadImgSrc = ref('')
  const uploadType = ref(false) // 是否上传
  // 上传图片更换
  const uploadLocalImageFinsh = async () => {
    let file = uploadFile.value.files[0]
    if (file.size / 1024 / 1024 > 200) {
      return proxy.$message.warning("上传失败，图片大小请控制在 200M 以内")
    }
    // 第一次上传图片
    if (!uploadType.value) {
      console.log("上传图片")
      // 可以上传图片
      uploadType.value = true
      let {data} = await proxy.$http.post("/list/uploadImage",{
          file
        },{
          headers: {
            "Content-Type": "multipart/form-data",
          }
        })
        uploadImgSrc.value = data.data.url
        if (data.code !== 200) return proxy.$message.error("图片上传失败")
        proxy.$message.success("图片上传服务器成功")
    } else {
      console.log("修改图片")
      const formData = new FormData()
      formData.append("file", file)
      formData.append("imgUrl", uploadImgSrc.value)
      // 修改图片
      let {data} = await proxy.$http.post("/list/editUploadImage",formData,{
          headers: {
            "Content-Type": "multipart/form-data",
          }
        })
      uploadImgSrc.value = data.data.url
        if (data.code !== 200) return proxy.$message.error("图片上传失败")
        proxy.$message.success("图片修改成功")
    }
  }
  let showModal = ref(false)

  // 上传第三方图片链接
  // 取消上传
  const cancelUploadLink = () => {
    uploadImgSrc.value = ''
    showModal.value = false
  }
  // 确定上传
   const confirmUploadLink = () => {
    if (!uploadImgSrc.value) return proxy.$message.warning("请输入图片链接")
    showModal.value = false
   }

   // 从新闻中上传图片
   const imgId = ref(1)
   // 确定上传新闻中的图片
   const uploadLocalImg = () => {
      uploadImgSrc.value = localImg.value[imgId.value - 1]
      showModal.value = false
      proxy.$message.success(`选择了第 ${imgId.value} 张图片作为封面`)
   }

   // 发布新闻的标签类型
   const publish_tag = ref("产品") // 标签
   const tagList = [
    {
      label: "产品",
      value: "产品"
    },{
      label: "案例",
      value: '案例'
    },{
      label: '展会',
      value: '展会'
    },
    {
      label: '专利',
      value: '专利'
    },{
      label: '荣誉',
      value: '荣誉'
    }
   ]
 
  </script>
   
  <style lang="less" scoped>
  :deep(.tox-tinymce) {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
   
    .tox-statusbar {
      display: none;
    }
  }
  :deep(.n-card__content) {
     display: flex;
     align-items: center;
  }
  </style>